# -*- coding: utf-8 -*-
from api import api, GlobalError
from flask import jsonify, request
from model.good import Good
from werkzeug.exceptions import NotFound


@api.route('/good/<good_id>', methods=['GET'])
def get_good(good_id):
    '''
## 获取商品详情

    GET /api/good/<good_id>

Return:

* `GoodId` (string)
* `createTime` (long)
* `description` (string)
* `discount` (float)
* `images` (list of string)
* `bigImage` (string)
* `price` (double)
* `sales` (int)
* `title` (string)
* `updateTime` (long)
    '''
    try:
        good = Good.get({
            Good.Field._id: good_id
        }, [
            Good.Field.createTime,
            Good.Field.description,
            Good.Field.discount,
            Good.Field.images,
            Good.Field.bigImage,
            Good.Field.price,
            Good.Field.sales,
            Good.Field.title,
            Good.Field.updateTime
        ])
    except NotFound:
        return jsonify(stat=0, **GlobalError.PARAMETERS_INVALID), 403
    good.data['goodId'] = good.data.get(Good.Field._id)
    del good.data[Good.Field._id]
    return jsonify(stat=1, good=good.data)


@api.route('/good/search', methods=['POST'])
def search_good():
    '''
## 通过名字搜索商品

    POST /api/good/search

Return:

Return:

* `goods` (list of dict)
    * `goodId` (string)
    * `discount` (double) - 折扣，真实价格 = 原价格 * 折扣
    * `image` (string)
    * `price` (double)
    * `title` (string)
    * `updateTime` (long)
    '''
    name = request.form.get('name', None)
    if name is None:
        return jsonify(stat=0, **GlobalError.PARAMETERS_INVALID), 403
    try:
        good_list = Good.find({
            Good.Field.title: {
                '$regex': name
            }
        }, [
            Good.Field.discount,
            Good.Field.images,
            Good.Field.price,
            Good.Field.title,
            Good.Field.updateTime
        ])
    except:
        return jsonify(stat=1, goods=[])

    goods = []
    for good in good_list:
        good['image'] = good.get(Good.Field.images)[0]
        del good[Good.Field.images]
        good['goodId'] = good.get(Good.Field._id)
        del good[Good.Field._id]
        goods.append(good)
    return jsonify(stat=1, goods=goods)
